package com.example.myone.Broadcast;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.SeekBar;

import com.example.myone.Entity.Music;
import com.example.myone.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

@SuppressLint("StaticFieldLeak")
public class MusicManager {
    private static MusicManager instance;
    private static MediaPlayer mediaPlayer;
    private static final Handler handler = new Handler();
    private static final String CHANNEL_ID = "radio_music_channel";
    private static final int NOTIFICATION_ID = 1;
    private static NotificationManager notificationManager;
    private static RemoteViews notificationLayout;
    private static Notification notification;

    private static Context context;
    private static SeekBar seekBar;
    private static ImageView buttonPlayPause;
    private static String author;
    private static String title;
    private Music music;

    private MusicManager(Context context) {
        MusicManager.context = context.getApplicationContext();
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        createNotificationChannel();
        title = "初始化";
        author = "初始化";
        this.music = new Music();
    }

    public static synchronized MusicManager getInstance(Context context) {
        if (instance == null) {
            instance = new MusicManager(context);
        }
        return instance;
    }

    public void initMediaPlayer(Music music, String title, String author) {
        if (music.id != this.music.id) {
            // 属性赋值
            MusicManager.title = title;
            MusicManager.author = author;
            this.music = music;
            try {
                // 创建临时文件
                File tempAudioFile = File.createTempFile(
                        "temp_music", ".mp3", context.getCacheDir());
                // 将字节数组写入临时文件
                FileOutputStream fos = new FileOutputStream(tempAudioFile);
                fos.write(music.bytes);
                fos.close();
                // 初始化 MediaPlayer
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                        .setUsage(AudioAttributes.USAGE_MEDIA)
                        .build());
                mediaPlayer.setDataSource(context, Uri.fromFile(tempAudioFile));
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Radio Music Channel";
            String description = "Channel for radio music playback";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            channel.enableLights(true);
            channel.setLightColor(Color.RED);
            channel.enableVibration(false);
            notificationManager.createNotificationChannel(channel);
        }
    }

    public static void showNotification() {
        boolean isPlaying = mediaPlayer.isPlaying();
        // 创建 RemoteViews 并设置其中的内容
        notificationLayout = new RemoteViews(context.getPackageName(), R.layout.radio_pager_music_notification);
        notificationLayout.setTextViewText(R.id.music_title, MusicManager.title);
        notificationLayout.setTextViewText(R.id.music_author, MusicManager.author);
        // 根据播放状态设置播放/暂停按钮图标
        int playPauseIconRes = isPlaying ? R.drawable.ic_pause_music : R.drawable.ic_play_music;
        notificationLayout.setImageViewResource(R.id.music_player, playPauseIconRes);
        // 设置播放暂停按钮的点击事件,发送广播
        Intent playPauseIntent = new Intent(context, NotificationReceiver.class);
        playPauseIntent.setAction("com.example.ACTION_PLAY_PAUSE"); // 标识此意图用于播放或暂停音乐的功能
        PendingIntent playPausePendingIntent =
                PendingIntent.getBroadcast( // 创建一个待处理广播意图，点击通知中的播放暂停按钮时触发
                        context, 0, playPauseIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
        notificationLayout.setOnClickPendingIntent(R.id.music_player, playPausePendingIntent);
        // 构建通知
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notification = new Notification.Builder(context, CHANNEL_ID)
                    .setSmallIcon(android.R.drawable.ic_media_play)
                    .setCustomContentView(notificationLayout)
                    .setOngoing(true)
                    .build();
        }
        // 发送通知
        notificationManager.notify(NOTIFICATION_ID, notification);
        // 更新进度条等其他视图
        updateProgressBar();
        updateSeekBar();
    }
    public void playPauseMusic() {
        if (mediaPlayer != null) {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause(); // 暂停音乐
            } else {
                mediaPlayer.start(); // 播放音乐
                updateProgressBar(); // 更新通知进度条
                updateSeekBar(); // 更新弹窗进度条
            }
            updateButtonPlayPause(); // 更新弹窗按钮
            showNotification(); // 更新通知
        }
    }

    private static void updateProgressBar() {
        // 创建一个新的 Runnable 对象
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 检查 mediaPlayer 是否不为空且正在播放
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    // 计算当前播放进度的百分比
                    int progress = (int) (((float) mediaPlayer.getCurrentPosition() / mediaPlayer.getDuration()) * 100);
                    // 更新通知中的进度条
                    notificationLayout.setProgressBar(R.id.music_progress_bar, 100, progress, false);
                    // 发送通知以更新显示
                    notificationManager.notify(NOTIFICATION_ID, notification);
                    // 每隔1秒更新一次音乐播放进度
                    handler.postDelayed(this, 1000);
                }
            }
        };
        // 等待1秒后执行
        handler.postDelayed(runnable, 1000);
    }



    private static void updateSeekBar() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 如果音乐播放器存在且正在播放，并且进度条不为null
                if (mediaPlayer != null && mediaPlayer.isPlaying() && seekBar != null) {
                    // 获取当前播放位置
                    int progress = mediaPlayer.getCurrentPosition();
                    // 更新进度条位置
                    seekBar.setProgress(progress);
                    // 每隔1秒更新一次音乐播放进度
                    handler.postDelayed(this, 1000);
                }
            }
        };
        // 等待1秒后执行
        handler.postDelayed(runnable, 1000);
    }

    public void setSeekBar(SeekBar seekBar) {
        MusicManager.seekBar = seekBar;
        if (mediaPlayer != null) {
            seekBar.setMax(mediaPlayer.getDuration());
            int progress = mediaPlayer.getCurrentPosition();
            seekBar.setProgress(progress);
        }
    }

    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }


    public void setButtonPlayPause(ImageView buttonPlayPause) {
        MusicManager.buttonPlayPause = buttonPlayPause;
        if (mediaPlayer != null) {
            updateButtonPlayPause();
            showNotification();
        }
    }

    private static void updateButtonPlayPause() {
        if (mediaPlayer.isPlaying()) {
            buttonPlayPause.setImageResource(R.drawable.ic_pause_music);
        } else {
            buttonPlayPause.setImageResource(R.drawable.ic_play_music);
        }
    }
}

